package com.tuanzi.loan.web.bean.statistics;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import lombok.Data;
import lombok.EqualsAndHashCode;

import org.joda.time.DateTime;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.service.statistics.NginxLinkStatService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.statistics.NginxLinkStatRequest;
import com.tuanzi.loan.vo.response.statistics.NginxLinkStatResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.statistics.NginxLinkStatistisLazyDataModel;

/**
 * nginx链接统计
 * @author weibifeng 
 */
@Debug
@Data
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class NginxLinkStatBean extends JSFListingBean<NginxLinkStatRequest, NginxLinkStatResponse> {
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
    @Autowired
    NginxLinkStatService nginxLinkStatService;
    
    private StreamedContent xlsFile;
    
    public StreamedContent downloadExcel() throws UnsupportedEncodingException {
    	InputStream input = new ByteArrayInputStream(nginxLinkStatService.getExcel($).getBytes("GBK"));
		String fileName = System.currentTimeMillis() + ".csv";
		xlsFile = new DefaultStreamedContent(input, "application/vnd.ms-excel;charset=gb2312", fileName);
    	return xlsFile;
    }

    @PostConstruct
    private void init() {
        initLazyDataModel();
        initList();
    }

    private void initList(){
        
    }

    public void onFlushCache(){
        
        initList();
        addInfoMessage("缓存更新成功!");
    }

    public void onReset() {
        initLazyDataModel();
    }

    public void onRefresh(){
        lazyDataModel = new NginxLinkStatistisLazyDataModel($);
        addSuccessfullyMessage();
    }

    private void initLazyDataModel() {
        $ = new NginxLinkStatRequest();
        
        // 初始化默认当前日期
        Date date = null;
        try {
			date = sdf.parse(sdf.format(new DateTime().plusDays(-1).toDate()));
			$.setStartDate(date);
	        $.setEndDate(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        lazyDataModel = new NginxLinkStatistisLazyDataModel($);
    }
    
}




